import { useRef, useContext, useMemo } from "react";
import { Bubble } from "@ant-design/x";
import { Flex } from "antd";
import "./index.css";
import AiChatContext from "@/common/context/aiChatContext.js";
import { UserOutlined } from "@ant-design/icons";
import { Typography } from "antd";
import markdownit from "markdown-it";
import { themeStore } from "@/common/store/index";

const { getters } = themeStore();

const md = markdownit({ html: true, breaks: true });

const renderMarkdown = (content) => (
  <Typography>
    <div dangerouslySetInnerHTML={{ __html: md.render(content) }} />
  </Typography>
);

// 角色配置
const roles = {
  system: {
    placement: "start",
    avatar: {
      icon: <UserOutlined />,
      style: {
        background: "#fde3cf",
      },
    },
    typing: {
      step: 5,
      interval: 20,
    },
    style: {
      maxWidth: 600,
    },
    messageRender: renderMarkdown,
  },

  user: {
    placement: "end",
    avatar: {
      icon: <UserOutlined />,
      style: {
        background: "#87d068",
      },
    },
  },
};

const bubbleStyles = {
  content: {
    backgroundColor: getters.getBubbleBgColor()[getters.getTheme()],
  },
};

const ChatList = () => {
  const context = useContext(AiChatContext);

  const chatList = useMemo(
    () =>
      context.chatX.map((item) => {
        return {
          key: item.chatId,
          loading: !item.content,
          role: item.role,
          content: item.content,
          styles: bubbleStyles,
        };
      }),
    [context.chatX]
  );

  const listRef = useRef(null);

  return (
    <Flex vertical gap="small" className="chat-list">
      <Bubble.List
        ref={listRef}
        styles={bubbleStyles}
        style={{
          maxHeight: 600,
          paddingRight: 20,
        }}
        roles={roles}
        items={chatList}
      />
    </Flex>
  );
};

export default ChatList;
